from model import Model, Dao
from bson.dbref import DBRef

class OrderItem(Model):
    def __init__(self, _dict):
        Model.__init__(self, _dict)
    
        self.quantity = _dict['quantity']

        # associate fields
        self.item = _dict['item']
        self.order = _dict['order']
        
class OrderItemDao(Dao):
    def __init__(self):
        Dao.__init__(self, OrderItem)
        self.collection = 'order_items'        

        # associates { field name : collection name }
        self.ref_collections = {'order':'orders', 'item':'items'}
    
class Order(Model):
    def __init__(self, _dict):
        Model.__init__(self, _dict)
        
        self.title = _dict['title']
        self.created = _dict['created']
        self.status = _dict['status'] # 0: temp 

        # associate fields
        self.user = _dict['user']
        #self.company = _dict['company']

class OrderDao(Dao):
    def __init__(self):
        Dao.__init__(self, Order)
        self.collection = 'orders'

        # associates { field name : collection name }
        self.ref_collections = {'user':'users'}

    def remove(self, model):
        """
        Arguments:
            model -- dict type or Model object type
        Return:
            A document (dict) describing the effect of the remove or None if write acknowledgement is disabled.
        """
        if isinstance(model, dict):
            _ref = DBRef(self.collection, model['_id'])
            self.db.remove('order_items', query={'order_ref':_ref})
        else:
            _ref = DBRef(self.collection, model._id)
            self.db.remove('order_items', query={'order_ref':_ref})
            
        return Dao.remove(self, model)

        
if __name__ == '__main__':
    # create table
    #db.drop_all()
    #db.create_all()
    pass
